package com.dreambook.android.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.dreambook.android.R;
import com.dreambook.android.db.DreamBookColumns;
import com.dreambook.android.db.DreamBookQuery;
import com.dreambook.android.model.DreamBook;
import com.dreambook.android.util.Config;

public class HomeActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
	private ListView listView;
	private ProgressDialog progress;
	private Cursor mCursor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		listView = (ListView) findViewById(R.id.list);
		listView.setOnItemClickListener(this);
		getSupportLoaderManager().initLoader(DreamBookQuery._TOKEN, null, this);

	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {

		switch (id) {
		case DreamBookQuery._TOKEN:
			progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);
			Uri uri = DreamBook.CONTENT_URI.buildUpon().appendPath(Config.DISTINCT).build();

			return new CursorLoader(HomeActivity.this, uri, DreamBookQuery.PROJECTION, null, null, DreamBook.DREAMBOOK_TYPE_SORT);
		default:
			return null;
		}

	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		switch (loader.getId()) {
		case DreamBookQuery._TOKEN:
			progress.dismiss();
			ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor,
					new String[] { DreamBookColumns.DREAMBOOK_TYPE.getName() }, new int[] { android.R.id.text1 });

			listView.setAdapter(adapter);

			mCursor = cursor;
			break;
		default:
			break;
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (mCursor != null && mCursor.moveToPosition(position)) {
			String type = mCursor.getString(DreamBookQuery.DREAMBOOK_TYPE);
			Intent intent = new Intent(HomeActivity.this, ListDreembookActivity.class);
			intent.putExtra(Config.TYPE, type);
			startActivity(intent);
		}

	}
}